package com.shiliao.app.activity.interlocution.ui;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;

import com.shiliao.app.R;
import com.shiliao.app.activity.MainActivity;
import com.shiliao.app.activity.index.adapter.MyAdapter;
import com.shiliao.app.activity.index.ui.SearchActivity;
import com.shiliao.app.activity.interlocution.dialog.QuestionDialog;
import com.shiliao.app.activity.interlocution.dialog.SimilarQuestionDialog;
import com.shiliao.app.activity.interlocution.entity.InterlocutionEntity;
import com.shiliao.app.activity.interlocution.presenter.InterLocutionPresenter;
import com.shiliao.app.activity.interlocution.view.InterlocutionView;
import com.shiliao.app.manager.MessageEventManager;
import com.shiliao.app.manager.YMUserManager;
import com.shiliao.app.weight.DragTV;
import com.yimei.framework.base.ui.BaseFragment;
import com.yimei.framework.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yinzhiqiang on 2017/9/6.
 */

public class InterlocutionFragment extends BaseFragment implements InterlocutionView,
        MainActivity.IPageChangedListener, DragTV.floatClick, View.OnClickListener {

    private List<BaseFragment> fragmentList;

    @BindView(R.id.viewpager_ShouYe)
    ViewPager mViewPager;

    @BindView(R.id.mTabLayout)
    TabLayout mTabLayout;

    @BindView(R.id.float_image)
    DragTV floatImage;
    private MyAdapter myAdapter;
    private List<String> stringList;
    private QuestionDialog dialog;
    private SimilarQuestionDialog similarQuestionDialog;
    private PopupWindow myPopup;
    private Button btnSelQuestion;
    private Button btnNewQuestion;
    private String userId;
    private String conten;
    private InterLocutionPresenter interLocutionPresenter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_interlocution;
    }

    @Override
    public void onPageChanged(int position) {
        if (MainActivity.getCurrentView() == MainActivity.POSITION_INTERLOCUTION) {
            if (getView() == null && getActivity() != null) {
                mContext = getActivity();
                initFragment();
            } else if (!isInit
                    && getView() != null) {
                //     initFragment();
            } else if (isInit && getView() != null) {
                //     requestData();
                //   initFragment();
            }
        }
    }

    @Override
    protected void initFragmentView() {
        super.initFragmentView();
        initFragment();
    }

    private void initFragment() {
        isInit = true;
        interLocutionPresenter = new InterLocutionPresenter(this);
        floatImage.setClickLister(this);
        LogUtil.e("yjl", "===IndexFragment===init");
        initDatat();
    }

    @OnClick(R.id.index_search)
    public void serachProble() {
        Intent intent = new Intent(getContext(), SearchActivity.class);
        intent.putExtra("from", "interLocution");
        toActivity(intent);
    }

    private void initDatat() {
        userId = YMUserManager.getUserId(getContext());//获取userId

        fragmentList = new ArrayList<BaseFragment>();
        stringList = new ArrayList<>();

        stringList.add("常见问题");
        stringList.add("最新问题");
        stringList.add("我的问题");

        fragmentList.add(new CommonProblemFragment());
        fragmentList.add(new LatestProblemFragment());
        fragmentList.add(new MyQuestionFragment());

        myAdapter = new MyAdapter(getChildFragmentManager(), fragmentList, stringList);
        mViewPager.setAdapter(myAdapter);
        //设置预加载
        // mViewPager.setOffscreenPageLimit(3);
        //绑定ViewPager
        mTabLayout.setupWithViewPager(mViewPager);

        //TabLayout绑定adapter
        mTabLayout.setTabsFromPagerAdapter(myAdapter);

    }

    @Override
    public void Click() {
        dialog = new QuestionDialog(getActivity());
        dialog.show(false);
        dialog.showKeyBoard();
        dialog.setComfirn(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conten = dialog.getContent();
                if (!TextUtils.isEmpty(conten)) {
                    showLoadingView();
                    interLocutionPresenter.request(conten, userId);
                    dialog.hideKeyboard();
                } else {
                    showToast("请输入要您的问题");
                }
                LogUtil.e("yzq", conten);
            }
        });
    }


    @Override
    public void sumbitQuestion(final List<InterlocutionEntity> entities) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LogUtil.e("yzq", entities.size() + "...");
                if (entities.size() == 0) {//如果没有类似问题就请求提交新问题接口
                    showLoadingView();
                    interLocutionPresenter.requestSumbitNewQuestion(conten, userId);

                } else {//跳转新页面展示类似问题
                    //added by luyi
//                    ConfirmQuestion(entities);
                    similarQuestion(entities);
                }
            }
        });
    }

    public void similarQuestion(List<InterlocutionEntity> entities) {
        dialog.dismiss();
        similarQuestionDialog = new SimilarQuestionDialog(getActivity(), entities);
        similarQuestionDialog.show(false);
        similarQuestionDialog.reqNewQuestion(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadingView();
                interLocutionPresenter.requestSumbitNewQuestion(conten, userId);
            }
        });
    }

/*    private void ConfirmQuestion(final List<InterlocutionEntity> entities) {
        //View popupView = View.inflate(this, R.layout.popwindow_question_sel, null);
        View popupView= (LinearLayout)LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_question_sel, null);;

        dialog.dismiss();
        MessageEventManager.sendCancleDiaolg();
        if(myPopup==null) {

            //设置按钮
            btnNewQuestion= (Button) popupView.findViewById(R.id.btn_oldquestion);
            btnSelQuestion= (Button) popupView.findViewById(R.id.btn_newquestion);
            btnNewQuestion.setOnClickListener(this);
            btnSelQuestion.setOnClickListener(this);
            ((ImageView) popupView.findViewById(R.id.iv_close)).setOnClickListener(this);

            //设置 listview
            Iterator<InterlocutionEntity> it = entities.iterator();
            while (it.hasNext()) {
                it.next();
            }

            String[] strs = new String[] {"first", "second", "third", "fourth", "fifth"};
            ListView lv = (ListView) popupView.findViewById(R.id.question_lv);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(popupView.getContext(), R.layout.question_list, strs);
            lv.setAdapter(adapter);

            myPopup = new PopupWindow(popupView, 800, 1150);
        }

        myPopup.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f8f8f8")));
        myPopup.setFocusable(true);
        myPopup.setOutsideTouchable(true);

        myPopup.update();
        myPopup.showAtLocation(popupView, Gravity.CENTER,0,0);

    }*/

    @Override
    public void sumbitSuccess() {//提问成功关掉dialog
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (similarQuestionDialog != null) {
                    if (similarQuestionDialog.isShowing()) {
                        similarQuestionDialog.dismiss();
                    }
                }
                MessageEventManager.sendCancleDiaolg();
                mViewPager.setCurrentItem(2);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_oldquestion:
                showToast("old question!");
                break;
            case R.id.btn_newquestion:
                showLoadingView();
                interLocutionPresenter.requestSumbitNewQuestion(conten, userId);
                break;
            case R.id.iv_close:
                break;
        }
        myPopup.dismiss();
    }

}
